const { Service } = require('egg')
const cheerio = require('cheerio')
const { tableToList, getTerm } = require('../utils/tools')

module.exports = class GradeService extends Service {
  /**
   * * 课程成绩查询
   * @param {String} term 学期
   * @return {Array} *
   */
  async table(term = '') {
    const Cookie = this.ctx.state.Cookie
    const { sid } = this.ctx.data
    try {
      /* 在教务主页中获取成绩查询的链接 */
      const mainUrl = `${this.ctx.state.baseUrl}/xs_main.aspx?xh=${sid}&zgh=${sid}`
      const mainDom = await this.ctx.curl(mainUrl, {
        method: 'GET',
        headers: {
          Cookie,
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
          Host: this.ctx.state.baseUrl.replace('https://', ''),
        },
        timeout: 10000,
        rejectUnauthorized: false, // 忽略证书验证
      })
      const dom$ = cheerio.load(mainDom.data.toString())
      const apiUrl = encodeURI(`${this.ctx.state.baseUrl}/${dom$('a:contains("成绩查询")').first().attr('href')}`)
      // console.log('apiUrl', apiUrl)

      /* 获取关键查询参数 */
      const keyRes = await this.ctx.curl(apiUrl, {
        headers: {
          Cookie,
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
          Host: this.ctx.state.baseUrl.replace('https://', ''),
          Referer: `${this.ctx.state.baseUrl}/xs_main.aspx?xh=${sid}&zgh=${sid}`,
        },
        timeout: 5000,
        rejectUnauthorized: false, // 忽略证书验证
      })
      const key$ = cheerio.load(keyRes.data.toString())
      const __VIEWSTATE = key$('#__VIEWSTATE').attr('value')
      const __VIEWSTATEGENERATOR = key$('#__VIEWSTATEGENERATOR')
      /* end */

      const getOne = async (url, data, headers, t) => {
        const info = {}
        const res = await this.ctx.curl(url, {
          method: 'POST',
          data,
          headers,
          timeout: 5000,
          rejectUnauthorized: false, // 忽略证书验证
        })
        if (res.status === 200) {
          const tableList = tableToList(res.data.toString(), '#DataGrid1')
          const columnNeed = [1, 6, 3, 7, 2] // 需要提取的列序号

          for (let i = 1; i < tableList.length; i++) {
            const term_ = t
            if ((term_ in info) === false) { info[term_] = [] }
            const tem = []
            columnNeed.forEach((idx) => {
              if (idx === 3) { tem.push({ score: tableList[i][idx] }) }
              else { tem.push(tableList[i][idx]) }
            })
            info[term_].push(tem)
          }

          return info
        }
        return info
      }

      /* 获取的数据中缺少学期，只好按照学期获取 */
      const header = ['课程名称', '学分', '成绩', '绩点', '课程性质'] // 列名称
      let P = []
      const sub = (new Date().getFullYear() - Number(sid.slice(0, 4))) * 2
      for (let i = 1; i <= (sub > 10 ? 10 : sub); i++) {
        let t = getTerm(sid.slice(0, 4), i)
        if (term) t = term
        const d = {
          __VIEWSTATE,
          __VIEWSTATEGENERATOR,
          ddlXN: t ? `${t.split('-')[0]}-${t.split('-')[1]}` : '',
          ddlXQ: t ? t.split('-')[2] : '',
          txtQSCJ: 0,
          txtZZCJ: 100,
          Button1: '按学期查询',
        }
        const h = {
          Cookie,
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
          Host: this.ctx.state.baseUrl.replace('https://', ''),
          Referer: apiUrl,
          Origin: this.ctx.state.baseUrl,
        }
        if (term) P = [getOne(apiUrl, d, h, term)]
        else P.push(getOne(apiUrl, d, h, t))
      }
      const res = await Promise.all(P)
      /* end */

      let result = {}
      for (const i of res) {
        result = { ...result, ...i }
      }

      return { table: result, header }
    } catch (err) {
      console.log('err', err)
      throw err
    }
  }
}
